package com.aso.common.crash;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.Thread.UncaughtExceptionHandler;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Build;
import android.os.Environment;
import android.util.Log;

import com.aso.common.utils.FileUtils;
import com.itsdf07.alog.ALog;


/**
 * Created by sudf on 2017/9/13.
 */

public class CrashHandler implements UncaughtExceptionHandler {
    private static final String TAG = "CrashHandler";

    private static final boolean DEBUG = true;

    private static final String FILE_NAME = "crash";

    private static final String FLIE_NAME_SUFFIX = ".log";

    private UncaughtExceptionHandler mDefaultCrashHandler;

    private Context mContext;

    public CrashHandler() {

    }

    /**
     * 静态内部类单例
     *
     * @return
     */
    public static CrashHandler getInstance() {
        ALog.dTag(TAG, "get crash instance.");
        return InstanceHolder.sInstance;
    }

    private static class InstanceHolder {
        private static CrashHandler sInstance = new CrashHandler();
    }

    public void init(Context context) {
        ALog.dTag(TAG, "init UncaughtExceptionnHandler");
        mDefaultCrashHandler = Thread.getDefaultUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(this);
        mContext = context.getApplicationContext();
    }

    /**
     * 程序崩溃会调用该方法
     */
    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        try {
            ALog.dTag(TAG, "uncaughtException ...");
            dumpExceptionToSDCard(ex);
            // uploadExceptionToServer(ex);  需要把异常上传到服务器，编写逻辑 解除该行注释
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void dumpExceptionToSDCard(final Throwable ex) throws IOException {
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            if (DEBUG) {
                ALog.wTag(TAG, "sdcard unmounted,skip dump exception");
                return;
            }
        }

        File dir = new File(FileUtils.INNERSDPATH);
        if (!dir.exists()) {
            ALog.dTag(TAG, "log dir not exists. ready create");
            dir.mkdirs();

        }

        long current = System.currentTimeMillis();
        final String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(current));
        final File file = new File(FileUtils.INNERSDPATH + FILE_NAME + FLIE_NAME_SUFFIX);
        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(file)));
                    pw.println(time);
                    dumpPhoneInfo(pw, ex);
                    pw.close();
                } catch (Exception e) {
                    Log.e(TAG, "dump crash info failed : " + Log.getStackTraceString(e));
                }
            }
        }).start();
    }

    private void dumpPhoneInfo(PrintWriter pw, Throwable ex) throws NameNotFoundException {
        ALog.dTag(TAG, "dumpPhoneInfo ... start");
        PackageManager pm = mContext.getPackageManager();
        PackageInfo pi = pm.getPackageInfo(mContext.getPackageName(), PackageManager.GET_ACTIVITIES);
        pw.print("App version: ");
        pw.print(pi.versionName);
        pw.print('_');
        pw.println(pi.versionCode);

        //Android版本号
        pw.print("OS Version: ");
        pw.print(Build.VERSION.RELEASE);
        pw.print(" _ sdk: ");
        pw.println(Build.VERSION.SDK_INT);

        //手机制造商
        pw.print("Vendor: ");
        pw.println(Build.MANUFACTURER);

        //手机型号
        pw.print("Model: ");
        pw.println(Build.MODEL);

        //CPU架构
        pw.print("CPU ABI : ");
        pw.println(Build.CPU_ABI);
        pw.println();
        //异常信息
        ex.printStackTrace(pw);
    }

    private void uploadExceptionToServer(Throwable ex) {
        //上传到服务器逻辑代码
    }
}
